<?php
/**
 * Created by PhpStorm.
 * User: 快定
 * Date: 2021/9/13
 * Time: 13:40
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;


class LoginController extends Controller
{

    //登录页面展示
    public function index()
    {
        if (auth()->check()) {
            return view('admin.index.index');
        }
        return view('admin.login.login');
    }

    //登录验证
    public function login(Request $request)
    {
        $post = $this->validate($request, [
            'username' => 'required',
            'password' => 'required',
        ], [
            'username' => '账号不能为空！',
            'password' => '密码不能为空!',
        ]);
        $bool = auth()->attempt($post);
        if ($bool) {
            if (config('rbac.super') != $post['username']) {
                $userModel = auth()->user();
                $roleModel = $userModel->role;
                $authArr = $roleModel->auths->pluck('route_name', 'id')->toArray();
                session(['admin.auth' => $authArr]);
            } else {
                session(['admin.auth' => true]);
            }
            //登录成功
            return redirect(route('admin.index'));
        } else {
            //登录失败
            //withErrors 把信息写入到错误提示中 特殊的session laravel中叫 闪存
            //闪存 从设置好之后，只能在第一个http请求中获取，以后就没有了
            return redirect(route('admin.login'))->withErrors(['error' => '用户名或密码错误!']);
        }
    }
}